package Servlet;

import Entity.Friends;
import java.io.IOException;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.naming.Context;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author Clara
 */
public class PlayerDeleteServlet extends HttpServlet {
    @Resource
    private javax.transaction.UserTransaction utx;

    /**
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setAttribute("resultString", searchFriends(request.getParameter("userName"), request.getParameter("friendName")));

        // Now that the controller has gathered the data from the model,
        // pass the data onto the view to render it as JSON.
        RequestDispatcher view = request.getRequestDispatcher("/add_delete_view.jsp");
        view.forward(request, response);
    }

    //make user friend exist before deleting. returns a string that indicate whether delet was successful.
    private String searchFriends(String userName, String friendName) {
        String deleteString = "";

        try {
            //get context from context file.
            Context ctx = GetContext.getContext();
            EntityManager em = (EntityManager) ctx.lookup("persistence/LogicalName");
            //query for friend using user name and friend.
            Query p = em.createNamedQuery("Friends.findByUserNameAndfriend").setParameter("userName", userName).setParameter("friendName", friendName);
            List<Friends> results = p.getResultList();
            //If friend doesn't exist.
            if(results.isEmpty())
                deleteString = "Delete Fail.";
            //If friend exists.
            else{
                    deleteString = "Deleteing";
                    try{
                        utx.begin();
                        //make a new object and then merge with entity manager
                        Friends d =  new Friends(userName, friendName);
                        d = em.merge(d);
                        //remove the object
                        em.remove(d);
                        //update data string
                        deleteString = "Friend Deleted";
                        utx.commit();
                    } catch (Exception e) {
                Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
                throw new RuntimeException(e);
                }
            }
        } catch (Exception ex) {
            Logger.getLogger(CluesServlet.class.getName()).log(Level.SEVERE, null, ex);
        }

        return deleteString;
    }

    /**
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>

}